package com.erp.wallet.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.erp.wallet.service.IErpSellerStoreWalletOrderService;
import com.ruoyi.common.core.pay.AlipayConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;

@RestController
@RequestMapping("/pay/alipay")
public class AliPayController {

	@Autowired
    AlipayConfig alipayConfig;
//	@Autowired
//	IErpSysServiceMarketService iErpSysServiceMarketService;
	@Autowired
    IErpSellerStoreWalletOrderService iErpSellerStoreWalletOrderService;

	@RequestMapping("/callback")
	public void alipayNotify(HttpServletRequest request, HttpServletResponse response) {
		PrintWriter writer = null;
		try {
			Map<String, String> params = new LinkedHashMap<String, String>();
			// 这里拿到支付宝通知数据
			Map<String, String[]> requestParams = request.getParameterMap();
			for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
				String name = (String) iter.next();
				String[] values = (String[]) requestParams.get(name);
				String valueStr = "";
				for (int i = 0; i < values.length; i++) {
					valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
				}
				// 乱码解决，这段代码在出现乱码时使用
				// valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
				params.put(name, valueStr);
			}
			String tradeStatus = params.get("trade_status");
			String outTradeNo = params.get("out_trade_no"); // 商户订单号
			String buyerLogonId = params.get("buyer_logon_id");
			String appId = params.get("app_id");
			String tradeNo = params.get("trade_no"); // 支付宝交易号
			// 此处只列出来几个参数，如果有其他需要，可都获取出来
			// 调用SDK验证签名 (params,ALIPAY_PUBLIC_KEY,CHAR_SET,SIGNTYPE)
			String alipayPublicCertPath = alipayConfig.getAlipayPublicCertPath(); // 支付宝公钥证书
			boolean signVerified = AlipaySignature.rsaCertCheckV1(params, alipayPublicCertPath, "UTF-8", "RSA2");
			if (signVerified) {
				System.out.println("支付宝回调签名认证成功");
				// 支付成功
				if (tradeStatus.equals("TRADE_FINISHED") || tradeStatus.equals("TRADE_SUCCESS")) {
					try {

						// 在这里处理支付成功后的业务逻辑

						//根据订单号判断调用的service
						if (outTradeNo.startsWith("MK")) { //TODO  服务市场
//							ServiceDto serviceDto = new ServiceDto();
//							serviceDto.setAilOrderNumber(tradeNo);
//							serviceDto.setOrderNumber(outTradeNo);
//							iErpSysServiceMarketService.buyERPAmountOrder(serviceDto);
						} else if (outTradeNo.startsWith("ZZ")) { //TODO  增值服务
//							ServiceDto serviceDto = new ServiceDto();
//							serviceDto.setAilOrderNumber(tradeNo);
//							serviceDto.setOrderNumber(outTradeNo);
//							iErpSysServiceMarketService.buyServiceOrderSuccess(serviceDto);
						} else if (outTradeNo.startsWith("WA")) { // 钱包充值/提现
							iErpSellerStoreWalletOrderService.callback(outTradeNo, tradeNo);
						}

					} catch (Exception e) {
						System.out.println("支付宝回调业务处理报错");
						e.printStackTrace();
					}
				} else {
					System.out.println("没有处理支付宝回调业务");
				}
				try {
					writer = response.getWriter();
				} catch (IOException e) {
					e.printStackTrace();
				}
				writer.write("success"); // 一定要返回success
				writer.flush();
				return;
			} else {
				System.out.println("支付宝回调签名认证失败");
				writer.write("failure");
				writer.flush();
				return;
			}
		} catch (AlipayApiException e) {
			System.out.println("支付宝回调签名认证失败");
			e.printStackTrace();
			writer.write("failure");
			writer.flush();
			return;
		}
	}
}
